package com.jingdianjichi.subject.application.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.jingdianjichi.subject.application.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * mvc的全局处理
 * 
 * @author: ChickenWing
 * @date: 2023/10/7
 */
@Configuration
public class GlobalConfig extends WebMvcConfigurationSupport {

    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        converters.add(mappingJackson2HttpMessageConverter());
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**");
    }
       /**
     * 创建并配置MappingJackson2HttpMessageConverter对象
     * 该转换器用于处理HTTP请求和响应中的JSON数据序列化和反序列化
     *
     * @return 配置好的MappingJackson2HttpMessageConverter实例
     */
    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        // 配置ObjectMapper，设置JSON序列化和反序列化的行为
        ObjectMapper objectMapper = new ObjectMapper();
        // 禁用空对象序列化失败检查，允许序列化空对象
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 设置序列化时只包含非null值的字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 创建并返回配置好的转换器
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);
        return converter;
    }


}
